/*
 * Copyright © 2011 Nokia Corporation. All rights reserved.
 * Nokia and Nokia Connecting People are registered trademarks of Nokia Corporation. 
 * Oracle and Java are trademarks or registered trademarks of Oracle and/or its
 * affiliates. Other product and company names mentioned herein may be trademarks
 * or trade names of their respective owners. 
 * See LICENSE.TXT for license information.
 */ 

package com.nokia.example.wordpress.networking;

import com.nokia.example.wordpress.networking.Request;

/**
 * Operation to send a new blog post to the server.
 */
public class NewPostOperation extends NetworkOperation {

    /**
     * Listener interface
     */
    public interface Listener {

        /**
         * Returns the id of the new post.
         * @param blog
         * @param postId
         */
        public void newPostSent(Blog blog, String postId);
    }
    private static final String WP_NEW_POST = "metaWeblog.newPost";
    private Blog blog;
    private String title;
    private String description;
    private Listener listener;

    /**
     * Constructor
     * @param listener
     * @param blog Blog to post to
     * @param title Post title
     * @param description Post content
     */
    public NewPostOperation(Listener listener, Blog blog, String title, String description) {
        this.listener = listener;
        this.blog = blog;
        this.title = title;
        this.description = description;
    }

    /**
     * Starts the operation.
     */
    public void start() {
        Request req = new Request(WP_NEW_POST);
        req.addStringParam(blog.blogId);
        req.addStringParam(blog.blogUser);
        req.addStringParam(blog.blogUserPassword);
        req.addStructMember("title", title);
        req.addStructMember("description", description);
        req.addIntParam("1"); // publish: yes
        Network nw = new Network(this);
        nw.startHttpPost(blog.xmlrpcUrl, req.request());
    }

    /**
     * Parses the server response and calls the listener.
     * @param response
     */
    public void networkHttpPostResponse(String response) {
        try {
            NewPostParser handler = new NewPostParser();
            parse(response, handler);
            listener.newPostSent(blog, handler.postId);
        } catch (ParseError e) {
            listener.newPostSent(blog, null);
        }
    }
}
